package com.wusuowei.shiro_jwt_vue.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wusuowei.shiro_jwt_vue.mapper.FilesMapper;
import com.wusuowei.shiro_jwt_vue.model.po.Files;
import com.wusuowei.shiro_jwt_vue.model.vo.FileUploadInfo;
import com.wusuowei.shiro_jwt_vue.utils.MinioUtils;
import com.wusuowei.shiro_jwt_vue.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lgy
 */
@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FilesMapper fileMapper;

    @Autowired
    private MinioUtils minioUtils;


    /**
     * @description 通过md5获取文件
     * @param md5 md5型
     * @return {@link Files }
     * @author LGY
     * @date 2023/03/27 13:37
     */
    private Files getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        LambdaQueryWrapper<Files> queryWrapper = new LambdaQueryWrapper<Files>();
        queryWrapper.eq(Files::getFileMd5, md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }


    /**
     * @description 查找页面
     * @param pageNum 书籍页码
     * @param pageSize 页面大小
     * @param name 名称
     * @return {@link R }
     * @author LGY
     * @date 2023/03/27 16:00
     */
    @RequiresAuthentication
    @GetMapping("/page")
    public R findPage(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize,
                      @RequestParam(defaultValue = "") String name) {

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        // 查询未删除的记录
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return R.ok().setData(fileMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * @description 更新文件
     * @param files 文件夹
     * @return {@link R }
     * @author LGY
     * @date 2023/03/27 16:10
     */
    @RequiresAuthentication
    @PostMapping("/update")
    public R update(@RequestBody Files files) {
        return R.ok().setData(fileMapper.updateById(files));
    }

    @RequiresAuthentication
    @GetMapping("/detail/{id}")
    public R getById(@PathVariable Integer id) {
        return R.ok().setData(fileMapper.selectById(id));
    }

    @RequiresRoles(value = {"admin", "vip"}, logical = Logical.OR)
    @PostMapping()
    public R delete(@RequestBody FileUploadInfo fileUploadInfo) {
        try {
            minioUtils.deleteObject(fileUploadInfo.getFileType(), fileUploadInfo.getFileName());
        } catch (Exception e) {
            return R.error("文件删除失败");
        }
        fileMapper.deleteById(fileUploadInfo.getId());
        return R.ok();
    }

    @RequiresRoles(value = {"admin", "vip"}, logical = Logical.OR)
    @PostMapping("/del/batch")
    public R deleteBatch(@RequestBody List<FileUploadInfo> fileUploadInfos) {
        // select * from sys_file where id in (id,id,id...)
        List<Integer> collect = fileUploadInfos.stream().map(FileUploadInfo::getId).collect(Collectors.toList());
        for (FileUploadInfo fileUploadInfo : fileUploadInfos) {
            try {
                minioUtils.deleteObject(fileUploadInfo.getFileType(), fileUploadInfo.getFileName());
            } catch (Exception e) {
                return R.error("文件删除失败");
            }
        }
        fileMapper.deleteBatchIds(collect);
        return R.ok();
    }

}
